package com.google.code.virtualhockey.vhx.server.model

import com.google.code.virtualhockey.vhx.sds.STMetaData
import com.google.code.virtualhockey.vhx.sds.fields._
import com.google.code.virtualhockey.vhx.sds.STNamedEntity
import com.google.appengine.api.datastore.GeoPt
import org.apache.commons.codec.binary.Base64

/**
 * Represents an image (e.g. a Club logo).
 */
class Image( code: String,
             val mimeType: String,
             val data: Array[Byte],
             val width: Long,
             val height: Long ) extends STNamedEntity[Image] {

  setEntityName( code )

  /** Private no-arg constructor for SDS. */
  private def this() = this ( null, null, null, 0L, 0L )
}

object ImageMeta extends STMetaData[Image] {
  val cls    = classOf[Image]
  val kind   = "Image"
  val fields = List( new SShortText( this, "mimeType", false ),
                     new SLongBlob( this, "data" ),
                     new SLong( this, "width", false ),
                     new SLong( this, "height", false ) )

  /**
   * Creates a new Club instance from a CSV file line.
   */
  override def fromCsv( values: List[Any] ): Image = {

    // Remove line breaks from base64 encoded string and decode it into bytes
    //
    val imgBase64 = values(4).toString().replace( "\n", "" )
    val imgBytes = Base64.decodeBase64( imgBase64 )

    new Image( values(0).toString,
              values(1).toString,
              imgBytes,
              values(2).asInstanceOf[Long],
              values(3).asInstanceOf[Long] )
  }
}
